<template>
  <el-dialog
    v-model="visible"
    class="components-retail-add-or-update"
    :title="
      !dataForm.retailProdId
        ? $t('product.addNew')
        : $t('temp.modify')
    "
    :close-on-click-modal="false"
    @closed="handleDialogClose"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="auto"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('product.singleProductBar')"
        prop="barCode"
      >
        <el-input
          v-model="dataForm.barCode"
          maxlength="50"
          show-word-limit
          :placeholder="$t('product.noBarcode')"
        >
          <template #append>
            {{ $t("product.usedToQuickItem") }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('product.itemName')"
        prop="name"
      >
        <el-input
          v-model="dataForm.name"
          maxlength="60"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('product.singleProdPic')"
        prop="imgs"
        class="upload-box"
      >
        <ImgsUpload
          v-model="dataForm.imgs"
          :limit="5"
        />
        <span>{{ $t("admin.recommImgSize") }}800*800，{{
          $t("product.draggableSort")
        }}5{{ $t("marketing.piece") }}</span>
      </el-form-item>
      <el-form-item
        :label="$t('product.singleProdSpe')"
        prop="spec"
      >
        <el-input
          v-model="dataForm.spec"
          maxlength="30"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('product.singleProdClas')"
        prop="categoryId"
      >
        <el-col :span="8">
          <el-cascader
            v-model="category.selected"
            :options="category.list"
            :props="category.props"
            :disabled="pickerDisabled"
            change-on-select
            clearable
            @change="handleCategoryChange"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        :label="$t('product.singleProdUnit')"
        prop="unit"
      >
        <el-select
          v-model="dataForm.unit"
          :disabled="pickerDisabled"
          filterable
          allow-create
          clearable
          :placeholder="$t('product.pleaseSelectAUnit')"
        >
          <el-option
            v-for="item in unitOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('product.singleProd')"
        prop="costPrice"
      >
        <el-input
          v-model="dataForm.costPrice"
          type="number"
          oninput="if(value>10000000000)value=1"
          :max="10000000000"
          @change="costPriceChange"
        >
          <template #append>
            {{ $t("admin.dollar") }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('product.singleProdInve')"
        prop="stocks"
      >
        <el-input
          v-model="dataForm.stocks"
          type="number"
          maxlength="7"
          @change="stocksChange"
        />
      </el-form-item>
      <el-form-item
        :label="$t('product.supplier')"
        prop="supplierId"
      >
        <div
          v-if="!supplierName"
          class="default-btn"
          @click="selectSupplier"
        >
          {{
            $t("product.chooseSupplier")
          }}
        </div>
        <div
          v-if="supplierName"
          class="supplier-name"
        >
          {{ supplierName }}
          <el-icon
            class="supplier-close"
            @click="handleClose"
          >
            <CloseBold />
          </el-icon>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
    <!-- 供应商选择弹窗-->
    <SupplierSelect
      v-if="supplierSelectVisible"
      ref="supplierSelectRef"
      :is-single="true"
      @refresh-select-supplier="supplierSelectHandle"
    />
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { treeDataTranslate, idList } from '@/utils/index'
import { unitOption } from '@/utils/unitOption'
import { Debounce } from '@/utils/debounce'
import ImgsUpload from '@/components/imgs-upload/index.vue'
import SupplierSelect from './components/supplier-select.vue'

const emit = defineEmits(['refreshDataList'])

onMounted(() => {
  getCategoryList()
})

const visible = ref(false)
const pickerDisabled = ref(false)

const dataForm = ref({
  retailProdId: null,
  shopId: null,
  barCode: null,
  name: null,
  pic: null,
  imgs: null,
  spec: null,
  categoryId: null,
  unit: null,
  costPrice: 0.00,
  stocks: 0,
  status: 1,
  supplierId: null,
  version: null,
  createTime: null,
  updateTime: null,
  deleteTime: null,
  supplierName: null
})
const dataFormRef = ref(null)

let validPic = false // 是否验证图片是否选择
// eslint-disable-next-line no-unused-vars
const validateSpace = (rule, value, callback) => {
  if (value === '') {
    callback()
  } else if (String(value).trim() === '') {
    callback(new Error($t('retailProd.barcodeNotEmpty')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateProd = (rule, value, callback) => {
  if (String(value).trim() === '') {
    callback(new Error($t('retailProd.productNameNotEmpty')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validate = (rule, value, callback) => {
  if (!/^[1-9]\d*$|^[1-9]\d*\.\d\d?$|^0\.\d\d?$/.test(value)) {
    callback(new Error($t('live.pleaseEnteThan0')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateNumber = (rule, value, callback) => {
  if (!/^[1-9]\d*$/.test(value)) {
    callback(new Error($t('formData.pleaseThan0')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateSpec = (rule, value, callback) => {
  if (/^\s+$/g.test(value)) {
    callback(new Error(($t('product.singleProductBar') + $t('canNotBeSpace'))))
  } else {
    callback()
  }
}
const dataRule = reactive({
  barCode: [
    { validator: validateSpace, trigger: 'blur' }
  ],
  imgs: [
    { required: true, message: $t('webInfoConfig.canNotBeEmpty'), trigger: 'blur' }
  ],
  name: [
    { required: true, message: $t('product.itemNameCanEmpty'), trigger: 'blur' },
    { validator: validateProd, trigger: 'blur' }
  ],
  costPrice: [
    { required: true, message: $t('live.pleaseEnteThan0'), trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ],
  spec: [
    { validator: validateSpec, trigger: 'blur' }
  ],
  stocks: [
    { required: true, message: $t('formData.pleaseThan0'), trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ]
})
// 分类树展示与回显
const category = reactive({
  list: [],
  selected: [],
  props: {
    value: 'categoryId',
    label: 'categoryName',
    expandTrigger: 'hover',
    checkStrictly: false
  }
})
const supplierName = ref('')

watch(() => dataForm.value.imgs, () => {
  if (validPic) {
    dataFormRef.value.validateField('imgs')
  }
})

const init = (retailProdId) => {
  validPic = false // 初始化不验证是否选择图片
  category.selected = []
  dataForm.value.pic = null
  dataForm.value.retailProdId = retailProdId || 0
  visible.value = true
  pickerDisabled.value = false
  getCategoryList().then(() => {
    dataFormRef.value.resetFields()
    if (dataForm.value.retailProdId) {
      http({
        url: http.adornUrl('/shop/retailProd/info/' + dataForm.value.retailProdId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.value = data
        supplierName.value = dataForm.value.supplierName
        category.selected = idList(category.list, dataForm.value.categoryId, 'categoryId', 'children').reverse()
      })
    }
  })
}
// 表单提交
const onSubmit = Debounce(() => {
  validPic = true
  dataFormRef.value.validate((valid) => {
    if (valid) {
      if (dataForm.value.imgs) {
        dataForm.value.pic = dataForm.value.imgs.split(',')[0]
      } else {
        ElMessage.error($t('publics.imageNoNull'))
        return false
      }
      pickerDisabled.value = true
      http({
        url: http.adornUrl('/shop/retailProd'),
        method: dataForm.value.retailProdId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        pickerDisabled.value = false
      })
    }
  })
})
const stocksChange = (stocks) => {
  dataForm.value.stocks = Math.round(stocks)
}
const costPriceChange = (costPrice) => {
  dataForm.value.costPrice = Number.parseFloat(costPrice)
}
// 获取分类信息
const getCategoryList = () => {
  dataForm.value.retailProdId = dataForm.value.retailProdId || 0
  return http({
    url: http.adornUrl('/prod/category/getCateListByRetProdId/' + dataForm.value.retailProdId),
    method: 'get',
    params: http.adornParams({
      maxGrade: 2
    })
  }).then(({ data }) => {
    // 仅展示含有三级分类的分类
    category.list = filterCategoryList(treeDataTranslate(data, 'categoryId', 'parentId'), 0)
  })
}
/**
 * 仅展示含有三级分类的分类
 */
const filterCategoryList = (categories, level) => {
  return categories.filter(item => {
    // 当前项是否含有下级分类
    if (item.children && item.children.length > 0) {
      item.children = filterCategoryList(item.children, level + 1)
    }
    return showCategory(item, level)
  })
}
const showCategory = (item, level) => {
  // 一级分类时，判断是否含有二级分类且二级分类下是否含有三级分类
  if (level === 0) {
    return item.children && item.children.length && item.children.some(el => showCategory(el, level + 1))
  }
  // 二级分类时，判断是否含有三级分类
  if (level === 1) {
    return !!(item.children && item.children.length)
  }
  return true
}
// 选择供应商
const supplierSelectRef = ref(null)
const supplierSelectVisible = ref(false)
const selectSupplier = () => {
  supplierSelectVisible.value = true
  nextTick(() => {
    supplierSelectRef.value?.init([{ supplierId: dataForm.value.supplierId }])
  })
}
const supplierSelectHandle = (data) => {
  if (data) {
    dataForm.value.supplierId = data[0].supplierId
    dataForm.value.supplierName = data[0].supplierName
    supplierName.value = dataForm.value.supplierName
  }
}
// 选择分类改变事件
const handleCategoryChange = (val) => {
  dataForm.value.categoryId = val[val.length - 1]
}
/**
* 品牌删除按钮
*/
const handleClose = () => {
  dataForm.value.supplierId = null
  supplierName.value = ''
  dataForm.value.supplierName = supplierName
}

/**
 * 关闭回调
 */
const handleDialogClose = () => {
  dataForm.value.supplierName = ''
  supplierName.value = ''
  supplierSelectVisible.value = false
}

defineExpose({
  init
})

</script>
<style scoped lang="scss">
.components-retail-add-or-update{
  .upload-box {
    :deep(.el-form-item__content){
      align-items: flex-start;
      flex-direction: column;
    }
  }
  .supplier-name {
    display: inline-block;
    max-width: 100%;
    position: relative;
    padding: 0 30px 0 10px;
    overflow: hidden;
    text-overflow:ellipsis;
    background-color: #e8effb;
    height: 32px;
    line-height: 30px;
    font-size: 12px;
    color: #155bd4;
    border: 1px solid #d0def6;
    border-radius: 4px;
    box-sizing: border-box;
    white-space: nowrap;
  }
  .supplier-close {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
  }
  .supplier-close::after {
    position: absolute;
    top: -1px;
    left: -1px;
    content: ' ';
    display: block;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    background: transparent;
    z-index: -1;
  }
  .supplier-close:hover {
    color: #fff;
  }
  .supplier-close:hover::after {
    background-color: #155bd4;
  }
}
</style>
